import { _decorator, Color, color, Component, instantiate, Label, Node, Prefab, ProgressBar, Sprite, SpriteFrame } from 'cc';
import { Context } from '../Context';
import { Core } from '../Core/Core';
import { EState, EEvent, EPlayerType, EPath } from '../Config/Enum';
import { PlayerManager } from '../PlayerManager';
import { SkillConfig } from '../Config/SkillConfig';
import { PlayerConfig } from '../Config/PlayerConfig';
import { ResourceManager } from '../Core/ResourceManager';
import { PicPath, PrefabPath } from '../Config/ResourceConfig';
const { ccclass, property } = _decorator;

@ccclass('FirstPlayerView')
export class FirstPlayerView extends Component {

    player
    playerPrefab
    playerName: Label
    currentPlayer: EPlayerType = EPlayerType.Tangmen
    ndSkills: Node
    playerList: EPlayerType[] = [EPlayerType.Shaolin, EPlayerType.Tangmen, EPlayerType.Emei, EPlayerType.Gaibang, EPlayerType.Wudang]
    lbWuxing: Label
    ndPlayerList: Node
    ndProperty: Node
    lbDesc: Label
    progressBar: ProgressBar

    currIndex: number = 1
    // 属性
    lbStrength: Label
    lbAgility: Label
    lbIntelligence: Label
    lbInnerPower: Label
    lbVitality: Label


    lbCriticalChance: Label
    lbCriticalDamage: Label
    lbAP: Label
    lbAttackSpeed: Label
    lbAttackRange: Label
    lbHP: Label
    lbWuxingEnhance: Label

    protected onLoad(): void {
        this.player = this.node.getChildByName('Player')
        this.playerName = this.node.getChildByName('PlayerName').getComponent(Label)
        this.ndSkills = this.node.getChildByName('Skills')
        this.lbWuxing = this.node.getChildByName('Wuxing').getComponent(Label)
        this.lbDesc = this.node.getChildByName('Desc').getComponent(Label)
        //this.progressBar = this.node.getChildByName('ProgressBar').getComponent(ProgressBar)

    }

    protected onDestroy(): void {
        
    }

    protected onEnable(): void {
        Core.Instance.event.on(EEvent.PlayerSelectedChange, this.onPlayerSelectedChange, this)
        
    }

    protected onDisable(): void {
        Core.Instance.event.off(EEvent.PlayerSelectedChange, this.onPlayerSelectedChange, this)
        
    }




    start() {
        console.log("selected player", Core.Instance.currentPlayer); 
        console.log("this.currIndex", this.currIndex);
        
        // 查看prefabMap里有没有唐门，没有的话持续尝试loadData
        this.tryLoadPlayer(Core.Instance.currentPlayer);


    }

    update(deltaTime: number) {
        
    }

    async tryLoadPlayer(player: EPlayerType, attempt: number = 0) {
        const path = EPath.PREFAB + "player/" + player;
        try {
            // 直接等待Promise解析
            this.playerPrefab = await ResourceManager.Instance.loadRes(path, Prefab) as Prefab;
            console.log("Loaded prefab:", this.playerPrefab);
            this.loadData(player);
        } catch (error) {
            console.error(`Error loading player ${player}:`, error);
            
            if (attempt < 10) {
                console.log(`Retrying... (attempt ${attempt + 1}/10)`);
                setTimeout(() => this.tryLoadPlayer(player, attempt + 1), 1000);
            } else {
                console.error("Failed to load player after 10 attempts");
            }
        }
    }



    async onPlayerSelectedChange(){
        await this.loadData(Core.Instance.currentPlayer)
    }

    loadData(player:EPlayerType){
        // 让ndPlayerList的currentPlayer高亮
        //this.ndPlayerList.getChildByName(player).getComponent(Sprite).color = new Color(255, 255, 255, 255)
        // 展示player动画
        this.player.removeAllChildren()
        //this.playerPrefab = await ResourceManager.Instance.loadRes(EPath.PREFAB+player, Prefab)
        this.playerPrefab = ResourceManager.Instance.getRes(PrefabPath[player])
        let node = instantiate(this.playerPrefab);
        node.getChildByName('Rage').active = false
        node.setScale(4, 4)
        this.player.addChild(node)
        node.getComponent(PlayerManager).initState(player)
        node.getComponent(PlayerManager).state = EState.IdleFront


        node.setPosition(0,0,0)

        // 展示player的名字、五行
        this.playerName.string = PlayerConfig[player].name
        this.lbWuxing.string = "五行： "+PlayerConfig[player].wuxing
        this.lbWuxing.color = color().fromHEX(PlayerConfig[player].wuxingColor);
        this.lbDesc.string = PlayerConfig[player].desc

        // 展示player武学
        // load ndSkills 下面的skill的icon和文字信息
        for (let i = 1; i < this.ndSkills.children.length+1; i++) {
            const element = this.ndSkills.children[i-1];

            element.getChildByName('Title').getComponent(Label).string = SkillConfig[player+'Skill'+i].name
            element.getChildByName('Desc').getComponent(Label).string = SkillConfig[player+'Skill'+i].desc
            
            //element.getChildByName('Icon').getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[player+'Skill'+i+'Icon']+"/icon")
            //element.getChildByName('Icon').getComponent(Sprite).spriteFrame = ResourceManager.Instance.loadRes(PicPath[player+'Skill'+i+'Icon'], SpriteFrame)

            // element.getChildByName('Level').getChildByName("Value").getComponent(Label).string = Core.Instance.players.get(player).skillData.skills[player+'Skill'+i].level.toString()

            ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[player+'Skill'+i+'Icon'])
            .then((spriteFrame) => {
                element.getChildByName('Icon').getComponent(Sprite).spriteFrame = spriteFrame;
            })
            .catch((error) => {
                console.error("加载武学图标失败:", error);
            });
        }

        


    }



    onButtonLeft(){

        this.currIndex--

        if (this.currIndex < 0) {
            this.currIndex = 0;
        }
        this.loadData(this.playerList[this.currIndex])

        Core.Instance.currentPlayer = this.playerList[this.currIndex]
    }

    onButtonRight(){

        this.currIndex++

        if (this.currIndex >= this.playerList.length) {
            this.currIndex = this.playerList.length-1;
        }
        this.loadData(this.playerList[this.currIndex])

        console.log("onButtonRight, currIndex", this.currIndex);
        console.log("this.playerList[this.currIndex]", this.playerList[this.currIndex]);
        Core.Instance.currentPlayer = this.playerList[this.currIndex]
    }
}


